/**
 * Copyright (C) 2022-2023
 * All rights reserved, Designed By www.tonetn.com
 * 注意：
 * 本软件为www.tonetn.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package com.xunyin.modules.goods.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.xunyin.common.service.impl.BaseServiceImpl;
import com.xunyin.common.utils.QueryHelpPlus;
import com.xunyin.dozer.service.IGenerator;
import com.xunyin.enums.*;
import com.xunyin.modules.device.domain.TDevice;
import com.xunyin.modules.device.service.mapper.TDeviceMapper;
import com.xunyin.modules.goods.domain.TGoods;
import com.xunyin.modules.goods.domain.TGoodsOrder;
import com.xunyin.modules.goods.domain.TTeaRoomContainerGoodsLink;
import com.xunyin.modules.goods.service.TGoodsOrderService;
import com.xunyin.modules.goods.service.dto.TGoodsOrderDto;
import com.xunyin.modules.goods.service.dto.TGoodsOrderQueryCriteria;
import com.xunyin.modules.goods.service.mapper.TGoodsMapper;
import com.xunyin.modules.goods.service.mapper.TGoodsOrderMapper;
import com.xunyin.modules.goods.service.mapper.TTeaRoomContainerGoodsLinkMapper;
import com.xunyin.modules.goods.service.param.GoodsOrderParam;
import com.xunyin.modules.membersuser.service.TMembersUserService;
import com.xunyin.modules.membersuser.vo.MembersDiscountVo;
import com.xunyin.modules.store.domain.TStore;
import com.xunyin.modules.store.service.TStoreService;
import com.xunyin.modules.storeroom.domain.TStoreRoom;
import com.xunyin.modules.storeroom.service.TStoreRoomService;
import com.xunyin.netty.NettyServerHandler;
import com.xunyin.utils.*;
import com.xunyin.utils.constants.ErrorEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;

/**
 * @author admin
 * @date 2022-10-28
 */
@Service
//@AllArgsConstructor
@RequiredArgsConstructor
@Slf4j
//@CacheConfig(cacheNames = "tGoodsOrder")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TGoodsOrderServiceImpl extends BaseServiceImpl<TGoodsOrderMapper, TGoodsOrder> implements TGoodsOrderService {

    private final IGenerator generator;

    @Autowired
    private TGoodsOrderMapper tGoodsOrderMapper;

    @Autowired
    private TDeviceMapper tDeviceMapper;

    @Autowired
    private TGoodsMapper tGoodsMapper;

    @Autowired
    private TTeaRoomContainerGoodsLinkMapper tTeaRoomContainerGoodsLinkMapper;

    @Autowired
    private TStoreService tStoreService;

    @Autowired
    private TStoreRoomService tStoreRoomService;

    @Autowired
    private TMembersUserService tMembersUserService;

    @Value("${project.tea.server}")
    private String projectTeaServer;

    @Value("${project.pay.server}")
    private String projectPayServer;

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(TGoodsOrderQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<TGoodsOrder> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", page.getList());
        map.put("totalElements", page.getTotal());
        return map;

    }


    @Override
    //@Cacheable
    public List<TGoodsOrder> queryAll(TGoodsOrderQueryCriteria criteria) {

        return baseMapper.selectList(QueryHelpPlus.getPredicate(TGoodsOrder.class, criteria));
    }

    /**
     * 补货登记设备打开指令
     * @param orderId
     * @return
     */
    @Override
    public String supplement(Integer orderId) {
        try {

            TGoodsOrder goodsOrder = tGoodsOrderMapper.selectById(orderId);

            LambdaQueryWrapper<TDevice> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TDevice::getStatus, 1);
            wrapper.eq(TDevice::getDeviceStatus, 1);
            wrapper.eq(TDevice::getDeviceType, 3);
            wrapper.eq(TDevice::getStoreId, goodsOrder.getTeaHouseId());
            // 发送指令到设备
            TDevice device = tDeviceMapper.selectOne(wrapper);
            if (device == null) {
                log.info("查不到设备记录：teaId: {}", goodsOrder.getTeaHouseName());
                return null;
            }
            log.info("deviceNo:{}, ContainerNum: {}", device.getDeviceNo(), goodsOrder.getContainerNum());
            if (goodsOrder.getContainerNum() <= 24) {
                CtrDeviceChannelEnum ctrDeviceChannelEnum = CtrDeviceChannelEnum.parse(goodsOrder.getContainerNum());
                NettyServerHandler.sendCmdBydeviceNo(device.getDeviceNo(), CtrDeviceAddrEnum.ADDR_NUM_2.getName(), ctrDeviceChannelEnum, CommandCodeEnum.OPEN);
            } else {
                CtrDeviceChannelEnum ctrDeviceChannelEnum = CtrDeviceChannelEnum.parse(goodsOrder.getContainerNum() - 24);
                NettyServerHandler.sendCmdBydeviceNo(device.getDeviceNo(), CtrDeviceAddrEnum.ADDR_NUM_3.getName(), ctrDeviceChannelEnum, CommandCodeEnum.OPEN);
            }

            log.info("发送指令到设备结束,设备编号：{}", device.getDeviceNo());


            // 设置货物是否补充
            goodsOrder.setSupplement(1);
            LambdaQueryWrapper<TGoodsOrder> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(TGoodsOrder::getId, orderId);
            tGoodsOrderMapper.update(goodsOrder, wrapper1);

            //teaHouseDao.updateSupplementStatus(orderId);
            log.info("容器号：{}，补货成功", goodsOrder.getContainerNum());
            //return CommonUtil.successJson();
            return "success";
        } catch (Exception e) {
            return ErrorEnum.E_100022.getErrorCode();
            //return CommonUtil.errorJson(ErrorEnum.E_100022);
        }

//        Map<String,String> Map=new HashMap<>();
//        Map.put("name",name);
//        Map.put("uid",uid);
//        Map.put("openid",openid);
//        teaHouseDao.modifyStock(Map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SortedMap<String, String> goodsOrderPay(GoodsOrderParam param) {
        SortedMap<String, String> resultMaps = new TreeMap<String, String>();
        Date nowDate = new Date();

        try {
            //生成订单号
            String orderNo = OrderNoUtil.getOrderNo("1012", "");//获取订单号

            //获取前端参数
            int goodsLinkId = param.getGoodsLinkId();
            String appUserId = param.getOpenId();
            String pageId = param.getPageId();
            int userId = param.getUserId();
            String userPhone = param.getUserPhone();
            //获取商品信息
            TTeaRoomContainerGoodsLink teaRoomContainerGoodsLink = tTeaRoomContainerGoodsLinkMapper.selectById(goodsLinkId);
            TGoods goods = tGoodsMapper.selectById(teaRoomContainerGoodsLink.getGoodsId());

            TStore tStore = tStoreService.getById(teaRoomContainerGoodsLink.getTeaHouseId());
            if (tStore == null) {
                log.info("会客厅没有找到，teaId: {}", teaRoomContainerGoodsLink.getTeaHouseId());
            }
            TStoreRoom tStoreRoom = tStoreRoomService.getById(teaRoomContainerGoodsLink.getTeaRoomId());
            if (tStoreRoom == null) {
                log.info("茶厅（茶室）没有找到，teaChildId: {}", teaRoomContainerGoodsLink.getTeaRoomId());
            }

            if (teaRoomContainerGoodsLink.getStock() == 0) {
                //return CommonUtil.errorJson(ErrorEnum.E_100015);
                resultMaps.put("flag", com.xunyin.enums.ErrorEnum.E_100015.getErrorCode());
            }

            int orderMoney = teaRoomContainerGoodsLink.getPrice();
            int payMoney = orderMoney;

            //是否可折扣商品
            Integer membersUserId = null;
            Double membersDiscount = null;

            if (goods.getIsDiscount() == 1) { // 1是 0 否
                //获取用户会员折扣信息
 /*               JSONObject memberParam = new JSONObject();
                memberParam.put("mainId", tStore.getMainId());
                memberParam.put("memberUserPhone", userPhone);*/
                MembersDiscountVo memberUser = tMembersUserService.getMembersDiscount(tStore.getMainId(), userPhone);

                if (memberUser.getIsMembers()) {
                    payMoney = new Double(Math.ceil(orderMoney * (memberUser.getMembersDiscount() / 10))).intValue();
                    membersUserId = memberUser.getMembersUserId();
                    membersDiscount = memberUser.getMembersDiscount();
                } else {
                    membersUserId = 0;
                }
            }

            //生成订单
            TGoodsOrder goodsOrder = new TGoodsOrder();
            goodsOrder.setMainId(tStore.getMainId());
            goodsOrder.setMainName(tStore.getMainName());
            goodsOrder.setAreaId(tStore.getAreaId());
            goodsOrder.setOrderTime(nowDate);
            goodsOrder.setOrderNo(orderNo);
            goodsOrder.setAppUserId(appUserId);
            goodsOrder.setAppType(1);
            goodsOrder.setGoodsId(goods.getId());
            goodsOrder.setGoodsName(goods.getGoodsName());
            goodsOrder.setGoodsDetail(goods.getGoodsDetail());
            goodsOrder.setContainerNum(teaRoomContainerGoodsLink.getContainerNum());
            goodsOrder.setTeaHouseId(teaRoomContainerGoodsLink.getTeaHouseId());
            goodsOrder.setTeaHouseName(tStore.getName());
            goodsOrder.setTeaChildId(teaRoomContainerGoodsLink.getTeaRoomId());
            goodsOrder.setTeaChildName(tStoreRoom.getStoreRoomName());
            goodsOrder.setAppOrderNo(orderNo);
            goodsOrder.setResultFlag(ResultFlag.WAIT_PAY.getValue());
            goodsOrder.setPayType(0);
            goodsOrder.setOrderMondey(orderMoney);
            goodsOrder.setPayMoney(payMoney);
            goodsOrder.setIsDiscount(goods.getIsDiscount());
            goodsOrder.setMembersUserId(membersUserId);
            goodsOrder.setMembersDiscount(membersDiscount);
            goodsOrder.setPageId(pageId);
            goodsOrder.setOrderStatus(OrderStatusEnum.WAIT_PAY.getValue());
            goodsOrder.setCreateTime(nowDate);
            goodsOrder.setCreateUserId(userId);
            goodsOrder.setStatus(CommonConst.ENABLE_FLAG);
            goodsOrder.setUserPhone(userPhone);
            tGoodsOrderMapper.insert(goodsOrder);

            String spbillCreateIp = "127.0.0.1";
            String payType = "3";

            //调用预下单接口
            String url = projectPayServer + "/trade/manager/wechat/payCreateOrder";
            String outNotifyUrl = projectTeaServer + "/miniapi/goods/goodsOrderPayNotify";

            JSONObject payParam = new JSONObject();
            payParam.put("payType", payType);
            payParam.put("businessId", tStore.getBusinessId());
            payParam.put("outOrderNo", orderNo);
            payParam.put("appNo", "teahouse");
            payParam.put("functionNo", "teahouse");
            payParam.put("outNotifyUrl", outNotifyUrl);
            payParam.put("body", "共享会客厅");
            payParam.put("detail", "共享会客厅");
            payParam.put("attach", "");
            payParam.put("totalFee", payMoney);
            payParam.put("spbillCreateIp", spbillCreateIp);
            payParam.put("tradeType", "JSAPI");
            payParam.put("productId", "001");
            payParam.put("limitPay", "");
            payParam.put("openid", appUserId);
            payParam.put("transactionId", "");

            log.info("支付下单参数 {}", payParam.toString());

            String result = HttpClientUtil.doPostJson(url, payParam.toString());
            BaseResult baseResult = com.alibaba.fastjson.JSON.parseObject(result, BaseResult.class);
            resultMaps.putAll((Map) baseResult.getData());
            resultMaps.put("payType", payType);//1-我的钱包；2-线下现金；3-微信；4-支付宝；5-二维码支付；6-其他
            resultMaps.put("flag", "success");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultMaps;
    }

    /**
     * 根据userId获取商品订单列表
     * @param param
     * @return
     */
    @Override
    public List<TGoodsOrder> listGoodsOrderByCreateUserId(GoodsOrderParam param) {
        LambdaQueryWrapper<TGoodsOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TGoodsOrder::getCreateUserId, param.getUserId())
                .eq(TGoodsOrder::getStatus, 1);
        List<TGoodsOrder> list = baseMapper.selectList(wrapper);
        return list;
    }


    @Override
    public void download(List<TGoodsOrderDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TGoodsOrderDto tGoodsOrder : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("主体ID", tGoodsOrder.getMainId());
            map.put("主体名称", tGoodsOrder.getMainName());
            map.put("区域id", tGoodsOrder.getAreaId());
            map.put("下单时间", tGoodsOrder.getOrderTime());
            map.put("微信订单号", tGoodsOrder.getTransactionId());
            map.put("订单号", tGoodsOrder.getOrderNo());
            map.put("用户手机号", tGoodsOrder.getUserPhone());
            map.put("应用用户ID(微信openid,支付宝userid)", tGoodsOrder.getAppUserId());
            map.put("应用类型", tGoodsOrder.getAppType());
            map.put("商品Id", tGoodsOrder.getGoodsId());
            map.put("商品与茶室关联Id", tGoodsOrder.getTeaRoomGoodsLinkId());
            map.put("产品名称", tGoodsOrder.getGoodsName());
            map.put("产品详情", tGoodsOrder.getGoodsDetail());
            map.put("商品图片", tGoodsOrder.getGoodsImages());
            map.put("柜台号", tGoodsOrder.getContainerNum());
            map.put("茶室ID", tGoodsOrder.getTeaHouseId());
            map.put("茶室名称", tGoodsOrder.getTeaHouseName());
            map.put("茶厅id", tGoodsOrder.getTeaChildId());
            map.put("茶厅名称", tGoodsOrder.getTeaChildName());
            map.put("支付订单号", tGoodsOrder.getAppOrderNo());
            map.put("支付结果", tGoodsOrder.getResultFlag());
            map.put("支付时间", tGoodsOrder.getPayTime());
            map.put("支付方式", tGoodsOrder.getPayType());
            map.put("订单金额", tGoodsOrder.getOrderMondey());
            map.put("支付金额", tGoodsOrder.getPayMoney());
            map.put("总优惠额度", tGoodsOrder.getAllDiscountMoney());
            map.put("会员用户Id", tGoodsOrder.getMembersUserId());
            map.put("会员折扣", tGoodsOrder.getMembersDiscount());
            map.put("优惠id", tGoodsOrder.getDiscountId());
            map.put("优惠方式", tGoodsOrder.getDiscountType());
            map.put("优惠额度", tGoodsOrder.getDiscountQuota());
            map.put("优惠事由", tGoodsOrder.getDiscountReason());
            map.put("退款订单号", tGoodsOrder.getRefundOrderNo());
            map.put("退款应用订单号", tGoodsOrder.getRefundAppOrderNo());
            map.put("退款时间", tGoodsOrder.getRefundTime());
            map.put("退款金额", tGoodsOrder.getRefundMoney());
            map.put("退款状态", tGoodsOrder.getReturnFlag());
            map.put("错误代码", tGoodsOrder.getErrCode());
            map.put("错误代码描述", tGoodsOrder.getErrCodeDesc());
            map.put("页面ID", tGoodsOrder.getPageId());
            map.put("是否结算", tGoodsOrder.getSettleFlag());
            map.put("是否可折扣商品 1是 0否", tGoodsOrder.getIsDiscount());
            map.put("备注", tGoodsOrder.getRemark());
            map.put("订单状态(0：待支付 1：已支付  2：已取消 3：已完成  4：已退款)", tGoodsOrder.getOrderStatus());
            map.put("创建日期", tGoodsOrder.getCreatedTime());
            map.put("更新日期", tGoodsOrder.getUpdatedTime());
            map.put("删除日期", tGoodsOrder.getDeletedTime());
            map.put("创建用户ID", tGoodsOrder.getCreatedUserId());
            map.put("更新用户ID", tGoodsOrder.getUpdatedUserId());
            map.put("订单状态", tGoodsOrder.getStatus());
            map.put("货物是否补充", tGoodsOrder.getSupplement());
            map.put("创建日期", tGoodsOrder.getCreateTime());
            map.put("更新日期", tGoodsOrder.getUpdateTime());
            map.put("删除日期", tGoodsOrder.getDeleteTime());
            map.put("创建用户ID", tGoodsOrder.getCreateUserId());
            map.put("更新用户ID", tGoodsOrder.getUpdateUserId());
            map.put(" isDel", tGoodsOrder.getIsDel());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
